package com.godme.gateway.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;

@RefreshScope
@Configuration
@Component
public class LimitService {

    @Value("${limit.threshold: 2}")
    private Integer threshold;

    private Timer timer = new Timer();

    private Map<String, AtomicInteger> globalAccessCount = new HashMap<String, AtomicInteger>();

    public boolean allowAccess(String primary){
        AtomicInteger accessCount = globalAccessCount.computeIfAbsent(primary, k -> new AtomicInteger(0));
        accessCount.incrementAndGet();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                accessCount.decrementAndGet();
            }
        }, 60000);
        return accessCount.get() <= threshold;
    }
}
